package com.xbongbong.paas.help.analysis.data;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.FormDataEsListPoJo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.service.CoUserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.parent.parse.data.FormDataUpdateGetAnalysisDataHelp;
import com.xbongbong.pro.enums.AmountFlagEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.help.FormDataAnalysisHelp;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author 魏荣杰
 * @date 2019/8/27 11:06
 * @since v4.3.0
 * @version v4.3.0
 */
@Component
public class FormDataAllListAnalysisDataHelp extends FormDataListAnalysisDataHelp {
    private static final Logger LOG = LoggerFactory.getLogger(FormDataAllListAnalysisDataHelp.class);

    @Resource
    private UserModel userModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private CoUserService coUserService;
    @Resource
    private FormDataUpdateGetAnalysisDataHelp formDataUpdateGetAnalysisDataHelp;
    @Resource
    private FormDataAnalysisHelp formDataAnalysisHelp;

    /**
     * 多form解析数据
     * @param formDataListVO
     * @throws XbbException
     */
    public void analysisDataList(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO, Map<Long, List<FieldAttrEntity>> formIdAndHeadListMap) throws XbbException {
        try {
            String corpid = formDataListDTO.getCorpid();

            Map<String, DepartmentEntity> departmentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            List<PaasFormDataEntityExt> formDataEsList = formDataListVO.getPaasFormDataESList();

            Map<Long, Map<String, FieldAttrEntity>> formAndExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (Map.Entry<Long, List<FieldAttrEntity>> entry : formIdAndHeadListMap.entrySet()) {
                Long key = entry.getKey();
                List<FieldAttrEntity> fieldAttrEntities = entry.getValue();
                formIdAndHeadListMap.put(key, fieldAttrEntities);
                Map<String, FieldAttrEntity> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (FieldAttrEntity item : fieldAttrEntities) {
                    explainMap.put(item.getAttr(), item);
                }
                formAndExplainMap.put(key, explainMap);
            }

            LinkResultDataVO linkResultDataVO = new LinkResultDataVO();
            Set<Object> linkDataSet = new HashSet<>();
            List<FormDataEsListPoJo> linkDataList = new ArrayList<>();
            List<Long> dataIdList = new ArrayList<>();
            for(PaasFormDataEntityExt item: formDataEsList) {
                dataIdList.add(item.getDataId());
            }
            //协同团队
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> paasCoUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Integer businessType = formDataListDTO.getBusinessType();
            Integer subBusinessType = formDataListDTO.getSubBusinessType();
            Set<String> userIds = new HashSet<>();
            if (UserTeamEnum.hasTeam(businessType)){
                Boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(),subBusinessType) || Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(),subBusinessType);
                userTeamService.getUserIdMapSetShow(userIds,dataIdList,corpid,businessType,isPublic,mainUserMap,coUserMap);
            } else {
                paasCoUserMap = coUserService.coUserMapShow(userIds,dataIdList, corpid);
            }
            formDataEsList.forEach(item -> userIds.add(item.getCreatorId()));

            Map<String, Object> param = BeanUtil.convertBean2Map(formDataListDTO, true);
            param.remove("del");
            param.put("userIdIn", userIds);
            param.put(ParameterConstant.COLUMNS, "user_id, name");
            param.put(ParameterConstant.LEAVE_MARKS, BasicConstant.ONE);
            List<UserEntity> userList = userModel.findEntitys(param);
            if(userList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
            }
            Map<String, UserEntity> userMap = new HashMap<>(userList.size());
            userList.forEach((item)->{
                userMap.put(item.getUserId(), item);
            });


            for (PaasFormDataEntityExt paasFormDataEsEntity: formDataEsList){
                Map<String, FieldAttrEntity> explainMap = formAndExplainMap.get(paasFormDataEsEntity.getFormId());
                JSONObject dataJsonObject = paasFormDataEsEntity.getData();
                dataJsonObject.put(FieldTypeEnum.ADDTIME.getAlias(), paasFormDataEsEntity.getAddTime());
                dataJsonObject.put(FieldTypeEnum.UPDATETIME.getAlias(), paasFormDataEsEntity.getUpdateTime());
                dataJsonObject.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEsEntity.getSerialNo());
                ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                BeanUtil.copyProperties(formDataListDTO, parseSingleRowDataDTO);
                dataJsonObject.put(FieldTypeEnum.CREATORID.getAlias(), paasFormDataEsEntity.getCreatorId());
                // 设置创建人
                if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                    parseSingleRowDataDTO.setCreatorId(dataJsonObject.getString(CustomerManagementEnum.CREATOR.getAttr()));
                } else {
                    parseSingleRowDataDTO.setCreatorId(paasFormDataEsEntity.getCreatorId());
                }
                setOwnerIdAndCoUserId(businessType, dataJsonObject, parseSingleRowDataDTO, paasFormDataEsEntity, mainUserMap, coUserMap, paasCoUserMap);
                dataJsonObject.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEsEntity.getDepartmentId());
                Long dataId = paasFormDataEsEntity.getId();
                paasFormDataEsEntity.setDataId(dataId);

                // 工单全部列表页特殊过滤，若某个模板的解释不可见，这个字段值变为空string处理
                for (String key : dataJsonObject.keySet()) {
                    if (!explainMap.containsKey(key)) {
                        // 超时的字段特殊处理，保留
                        if (!Objects.equals(key, "isRed")) {
                            dataJsonObject.put(key, "");
                        }
                    }
                }
                parseSingleRowDataDTO.setDataJsonObject(dataJsonObject);
                parseSingleRowDataDTO.setUserMap(userMap);
                parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                parseSingleRowDataDTO.setExplainMap(explainMap);
                parseSingleRowDataDTO.setListFlag(1);
                ParseSingleRowDataVO parseSingleRowDataVO = parseSingleRowData(parseSingleRowDataDTO);
                if(Objects.isNull(parseSingleRowDataVO)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
                JSONObject resultObject = parseSingleRowDataVO.getResult();
                if (!linkResultDataVO.getLinkDataSet().isEmpty()) {
                    linkResultDataVO.getLinkDataSet().forEach((item -> {
                        linkDataSet.add(item);
                    }));
                }
                // 为了在列表上面可以更新数据，加下这个
                ParseSingleRowDataVO updateDataVo = formDataUpdateGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
                if(Objects.isNull(updateDataVo)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                JSONObject sourceData = updateDataVo.getResult();
                sourceData.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEsEntity.getSerialNo());
                paasFormDataEsEntity.setSourceData(sourceData);
                formDataListVO.getHeadList().forEach((item) -> {
                    if (!resultObject.containsKey(item.getAttr())) {
                        if (FieldTypeEnum.SUB_FORM.getType().equals(item.getFieldType())
                                || FieldTypeEnum.UPLOAD.getType().equals(item.getFieldType())
                                || FieldTypeEnum.IMAGE.getType().equals(item.getFieldType())
                                || FieldTypeEnum.CONTACT_NUMBER.getType().equals(item.getFieldType())) {
                            resultObject.put(item.getAttr(), new ArrayList<>());
                        } else {
                            resultObject.put(item.getAttr(), "");
                        }
                    }
                });

                paasFormDataEsEntity.setData(resultObject);
                // 系统字段经历过一次权限的判断，所以这里加下重新赋值
                paasFormDataEsEntity.setSerialNo(resultObject.getString(FieldTypeEnum.SERIALNO.getAlias()));
                paasFormDataEsEntity.setCreatorId(resultObject.getString(FieldTypeEnum.CREATORID.getAlias()));
                paasFormDataEsEntity.setAddTime(resultObject.getLong(FieldTypeEnum.ADDTIME.getAlias()));
                paasFormDataEsEntity.setUpdateTime(resultObject.getLong(FieldTypeEnum.UPDATETIME.getAlias()));
                paasFormDataEsEntity.setOwnerId(resultObject.getString(FieldTypeEnum.OWNERID.getAlias()));
                if (Objects.isNull(resultObject.get(FieldTypeEnum.DEPARTMENTID.getAlias()))) {
                    paasFormDataEsEntity.setDepartmentId(null);
                }
                FormDataEsListPoJo formDataEsListPoJo = new FormDataEsListPoJo();
                BeanUtil.copyProperties(paasFormDataEsEntity, formDataEsListPoJo);
                linkDataList.add(formDataEsListPoJo);
            }

        } catch (XbbException e) {
            LOG.error("FormDataAllListAnalysisDataHelp.analysisDataList表单列表解析数据出错", e);
            throw e;
        } catch (Exception e) {
            LOG.error("FormDataAllListAnalysisDataHelp.analysisDataList表单列表解析数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    
    /**
     * 多form解析千份位
     */
    public void analysisAmountOfThousandBits(PaasFormDataEsListVO formDataListVO, Boolean analysisAmountOfThousandBitsWithOriginalValue, Map<Long, List<FieldAttrEntity>> formIdAndHeadListMap) {
        List<PaasFormDataEntityExt> paasFormDataEntityExts = formDataListVO.getPaasFormDataESList();

        Map<Long, Map<String, Object>> formAndExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (Map.Entry<Long, List<FieldAttrEntity>> entry : formIdAndHeadListMap.entrySet()) {
            List<FieldAttrEntity> fieldAttrEntityList = formDataListVO.getHeadList();
            Map<String, Object> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for(FieldAttrEntity fieldAttrEntity : fieldAttrEntityList){
                if(Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.NUM.getType())){
                    if(Objects.equals(fieldAttrEntity.getAmountFlag(), AmountFlagEnum.YES.getType())){
                        explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
                    }
                }
            }
            formAndExplainMap.put(entry.getKey(), explainMap);
        }

        for(PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts){
            Map<String,Object> explainMap = formAndExplainMap.get(paasFormDataEntityExt.getFormId());
            JSONObject resultJson = paasFormDataEntityExt.getData();
            Iterator iterator = resultJson.keySet().iterator();
            while (iterator.hasNext()){
                String attr = iterator.next().toString();
                formDataAnalysisHelp.analysisAmountOfThousandBitsNomal(resultJson,attr,explainMap,analysisAmountOfThousandBitsWithOriginalValue);
            }
            paasFormDataEntityExt.setData(resultJson);
        }
    }
}
